package cn.passlink.bletoothchat.Adapter;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import cn.passlink.bletoothchat.BleGATT.ClientUtils;
import cn.passlink.bletoothchat.R;

@SuppressLint("MissingPermission")
public class ScanFriendsAdapter extends BaseAdapter {
    private Context context;
    private List<BluetoothDevice> friendsList;        // 声明一个标志来跟踪当前的状态

    private ClientUtils clientUtils; // 蓝牙客户端工具


    public ScanFriendsAdapter(Context context, List<BluetoothDevice> friendsList,ClientUtils clientUtils) {
        this.context = context;
        this.friendsList = friendsList;
        this.clientUtils=clientUtils;
    }

    @Override
    public int getCount() {
        return friendsList.size();
    }

    @Override
    public Object getItem(int position) {
        return friendsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("MissingPermission")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.scan_friends_item, parent, false);

            holder = new ViewHolder();
            holder.usernameTextView = convertView.findViewById(R.id.scan_friend_name_TextView);
            holder.phoneTextView = convertView.findViewById(R.id.scan_friend_phone_TextView);
            holder.Connect=convertView.findViewById(R.id.scan_friends_item_connect);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        BluetoothDevice friends = friendsList.get(position);
        holder.usernameTextView.setText(friends.getName());
        holder.phoneTextView.setText(friends.getAddress());
        holder.Connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BluetoothDevice device = (BluetoothDevice) getItem(position);
                ConnectToDevice(device);
                Log.d("TAG","尝试连接中！！！");

            }
        });
        return convertView;
    }

    private static class ViewHolder {
        TextView usernameTextView;
        TextView phoneTextView;
        ImageView Connect;
    }


    private void ConnectToDevice( BluetoothDevice device){
        try {
            clientUtils.connectDevice(device);
        }catch (Exception e){
            Toast.makeText(context, "连接失败,请重试或者判断好连接目标!!", Toast.LENGTH_SHORT).show();
        }

    }

}
